from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
# 免除csrf认证
from django.views.decorators.csrf import csrf_exempt
import json
from app01.utils.form import TaskModelForm


def task_list(request):
    """任务列表"""
    form = TaskModelForm()
    return render(request,
                  'task_list.html',
                  {'form': form})


@csrf_exempt
def task_ajax(request):
    print(request.POST.get('n1'))

    json_str = json.dumps(request.POST)
    print(json_str)
    return HttpResponse(json_str)

@csrf_exempt
def task_add(request):
    print(request.POST)
    # 用户发送过来的数据进行校验(ModelForm校验)
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))
    from django.forms.utils import ErrorDict
    data_dict = {"status": False, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
